﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KBVault.DAL.Entities;
using KBVault.DAL.Repository;
using KBVault.Web.Infrastructure;


namespace KBVault.Web.Application.UC.Categories
{
    public partial class NewCategory : KBVaultBaseUserControl
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                lbPanelTitle.InnerText = "Add New Category";
                if ((this.Page as KBVaultAdminPage).ActiveCategoryId > 0)
                {
                    try
                    {
                        lbPanelTitle.InnerText = "Edit Category";
                        Category c = CategoryRepository.Get((this.Page as KBVaultAdminPage).ActiveCategoryId);
                        txtCategory.Text = c.Name;
                        chkHot.Checked = c.IsHot == 1;
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex.Message);
                        ShowExceptionMessage();
                    }
                }
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                Category c = new Category() { Name = txtCategory.Text, IsHot = ( chkHot.Checked ? 1 : 0 ) };
                if ((this.Page as KBVaultAdminPage).ActiveCategoryId > 0)
                {
                    c.Id = (this.Page as KBVaultAdminPage).ActiveCategoryId;
                    CategoryRepository.Update(c);
                }
                else
                {
                    CategoryRepository.Create(ref c);
                }
                if (!String.IsNullOrEmpty((this.Page as KBVaultAdminPage).ReturnUrl))
                    Response.Redirect((this.Page as KBVaultAdminPage).ReturnUrl);
                else
                    Response.Redirect("~/Application/CategoryOps.aspx?Op=List");
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                ShowExceptionMessage();
            }
        }
    }
}